package com.glut.library.controller;

import com.glut.library.entity.Users;
import com.glut.library.service.IUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 *  登陆注册控制器
 *
 * @author stubborn
 * @since 2024-12-13 16:28
 */
@RestController
@RequestMapping("/users")
public class UsersController {

    @Autowired
    private IUsersService userService;

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> loginData) {
        String username = loginData.get("username");
        String password = loginData.get("password");
        String role = loginData.get("role");

        Users user = userService.login(username, password, role);
        Map<String, Object> response = new HashMap<>();

        if (user != null) {
            response.put("role", user.getRole());
            response.put("username", user.getUsername());
            response.put("id", user.getId());
            response.put("message", "登录成功");
            return response; // 登录成功
        } else {
            response.put("message", "用户名或密码错误");
            return response; // 登录失败
        }
    }

    @PostMapping("/enroll")
    public Map<String, Object> register(@RequestBody Users user) {
        Map<String, Object> response = new HashMap<>();

        boolean success = userService.registerUser (user);

        if (success) {
            response.put("message", "注册成功");
            return response;
        } else {
            response.put("message", "用户名已存在");
            return response;
        }
    }

    @GetMapping("/findByUsername")
    public ResponseEntity<Users> findUserByUsername(@RequestParam String username) {
        Users user = userService.findByUsername(username);
        if (user != null) {
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}
